// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import Vuex from 'vuex';
import ElementUI from 'element-ui';
import './assets/theme/index.css';

import axios from 'axios';
import { library } from '@fortawesome/fontawesome-svg-core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import _ from 'lodash';

import VueContextMenu from 'vue-contextmenu';

import echarts from 'echarts';
import App from './App';
import router from './router';
//引入echarts
import OpenSeadragonView from 'open-seadragon-view';
import 'open-seadragon-view/dist/open-seadragon-view.css';
import GridLayoutButton from 'grid-layout-button';
import 'grid-layout-button/dist/grid-layout-button.css';
Vue.use(GridLayoutButton);
Vue.use(OpenSeadragonView);

import htmlToPdf from '@/client/libs/htmlToPdf';
// 使用Vue.use()方法就会调用工具方法中的install方法
Vue.use(htmlToPdf);

import '@/client/libs/directives';
import directives from '@/client/libs/directives-inserted';
Vue.use(directives);

Vue.use(ElementUI);
Vue.use(Vuex);
Vue.use(VueContextMenu);

library.add(faCoffee);

Vue.component('font-awesome-icon', FontAwesomeIcon);

Vue.config.productionTip = false;
//引入echarts
Vue.prototype.$echarts = echarts;

/*eslint spaced-comment:0*/
const formatState = {
  // 登录相关信息
  loginTime: null,
  authorization: null,
  // 平台信息
  platform: {
    name: null
  },
  // 登录用户机构信息
  institution: {
    id: null,
    name: null
  },
  // 登录用户信息
  user: {
    id: null,
    name: null,
    headImgUrl: null,
    isOutsideConsultationApplyPermissions: null,
    isDivisionConsultationApplyPermissions: null
  },
  // 当前用户权限列表
  permissionList: null,
  // 用户上次操作时间
  lastTime: null,
  // 当前路由值，用于确定左侧菜单选中值
  nowRoute: null,
  // 当前扫描状态
  scanStatus: null,
  config: null,
  diagnosis: {
    id: 0,
    pathologyId: ''
  },
 
};

//接口版本
const versionApi = {
  class: '/wonders-pathology-server/api',
  version: '/v1',
  versionControl: true
};

const store = new Vuex.Store({
  // 在刷新后从 sessionStorage 读取 state 数据
  state: {
    ...(sessionStorage.getItem('state')
      ? JSON.parse(sessionStorage.getItem('state'))
      : formatState),
    collapse: false,
    fullScreen: false,
    itemsDiagnosisListTabChangePage: 'myIssues',
    itemsDiagnosisListRowClickId: '',
    isEworld:false
  },
  mutations: {
    /*eslint no-unused-vars:0*/
    /* eslint no-param-reassign: ["error", { "props": false }] */
    // 初始化state
    stateInit(state) {
      /*eslint no-param-reassign:0*/
      state = formatState;
    },
    setisEworld(state,status){
      state.isEworld=status
    },
    // 设置用户登录时间
    loginTimeFlash(state) {
      state.loginTime = new Date().getTime();
    },
    // 刷新用户上次操作时间
    lastTimeFlash(state) {
      state.lastTime = new Date().getTime();
    },
    // 通用设置字段方法，慎用
    setPropertyGeneral(state, setter) {
      state[setter.key] = setter.value;
      // if (Object.prototype.isPrototypeOf.call(state, key)) {
      //   state[key] = value;
      // } else {
      //   throw new Error(`'${key}' is not found in state`);
      // }
    },
    setPlatform(state, platform) {
      state.platform = platform;
    },
    setInstitution(state, institution) {
      state.institution = institution;
    },
    setUser(state, user) {
      state.user = user;
      sessionStorage.setItem('state', JSON.stringify(state));
    },
    setPermissionList(state, permissionList) {
      state.permissionList = _.clone(permissionList);
    },
    // 侧边栏折叠
    hadndleCollapse(state, data) {
      state.collapse = data;
    },
    //是否全屏
    fullScreenChange(state, value) {
      state.fullScreen = value;
    },
    //院内诊断点击选择项
    itemsDiagnosisListTabChange(state, value) {
      state.itemsDiagnosisListTabChangePage = value;
    },
    //院内诊断点击选择项id
    itemsDiagnosisListRowClick(state, value) {
      state.itemsDiagnosisListRowClickId = value;
    }
  },
  actions: {},
  getters: {
    getAuthorization(state) {
      return state.authorization;
    }
  }
});

/* eslint-disable no-new */
const vue = new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  data: {
    isAxiosReady: false
  }
});

const axiosTemp = axios.create({
  baseURL: process.env.API_ROOT || 'http://localhost:3001'
});
// Add a response interceptor
axiosTemp.interceptors.request.use(
  config => {
    if (_.get(config.headers, 'defaultHeader', true)) {
      _.assign(config.headers, {
        'Content-Type': _.get(
          config.headers,
          'Content-Type',
          'application/json'
        ),
        authorization: _.get(
          config.headers,
          'authorization',
          vue.$store.getters.getAuthorization
        )
      });
      // _.assign(config.common, {
      //     'Accept': _.get(config.headers, 'Accept', 'application/x-www-form-urlencoded'),
      // });
    }
    if (
      !config.url.startsWith('http://') &&
      !config.url.startsWith('https://')
    ) {
      if (
        config.url.includes('/PROXY-Remote') &&
        config.url.startsWith('/PROXY-Remote')
      ) {
        config.url = config.url.split('/PROXY-Remote')[1];
      }
      if (versionApi.versionControl) {
        config.url = versionApi.class.concat(versionApi.version, config.url);
      }
    }
    delete config.headers.defaultHeader;
    return config;
  },
  error => Promise.reject(error)
);
axiosTemp.interceptors.response.use(
  response => {
    if (response.headers.authorization) {
      vue.$store.commit('setPropertyGeneral', {
        key: 'authorization',
        value: response.headers.authorization
      });
    }
    return response;
  },
  error => {
    if (error && error.response) {
      if (error.response.data.code === 401) {
        vue.$message.info('会话失效，请重新登录；');
        vue.$router.push('/newLogin');
      }
      return Promise.reject(error);
    }
  }
);

Vue.prototype.$axios = axiosTemp;
Vue.config.productionTip = false;
vue.isAxiosReady = true;
